package service

import (
	"fmt"
	"gin/common"
	"gin/common/constant"
	"gin/common/db/config"
	"gin/common/util"
	sysEntity "gin/system/entity"
	"github.com/gin-gonic/gin"
	"strings"
)

type SysMenuService struct {
}

//系统菜单
func GetRouters(c *gin.Context) {
	//TODO resultList
	var resultList []map[string]interface{}
	routers := make([]*sysEntity.RouterVo, 0)
	var menus []sysEntity.SysMenu
	sysUserEntity := &sysEntity.SysUserEntity{}
	if len(resultList) > 0 {
		userName := resultList[0]["userName"].(string)
		userId := resultList[0]["userId"].(int64)
		sysUserEntity.UserName = userName
		sysUserEntity.UserId = userId
	} else {
		common.ReturnError(c, constant.ERRORCODE(), "登录用户账号信息查询错误，请联系管理员处理！", "", int64(len("")))
	}

	if sysUserEntity.UserName == "admin" {
		err := config.GormDb.Model(&sysEntity.SysMenu{}).Table("sys_menu as m").Select("distinct m.menu_id, m.parent_id, m.menu_name, m.path,  m.component, m.query, m.visible, m.status, ifnull(m.perms,'') as perms, m.is_frame AS isFrame, m.is_cache, m.menu_type, m.icon, m.order_num, m.create_time").
			Where("m.menu_type in (" + "'M', 'C')" + " and m.status = 0").Scan(&menus).Error
		if err != nil {
			common.ReturnError(c, constant.ERRORCODE(), "超级管理员查询用户菜单失败，请联系系统管理员处理！", "", int64(len("")))
			panic("")
		}
	} else {
		//TODO 非超级管理员账号拥有的菜单信息
	}

	//TODO menus  查询 返回的结果集 数据，是一级菜单的信息，需要拼装 子集菜单
	menuAllList := getChildPerms(menus, 0)

	for _, menu := range menuAllList {
		//TODO
		fmt.Sprint(menu)
	}

	common.ReturnSucess1(c, constant.SUCCESSCODE(), "操作成功", routers)
}

// 对象转菜单树
func (svc *SysMenuService) InitZtree(menuList *[]sysEntity.SysMenu, roleMenuList *[]string, permsFlag bool) (*[]common.Ztree, error) {
	var result []common.Ztree
	isCheck := false
	if roleMenuList != nil && len(*roleMenuList) > 0 {
		isCheck = true
	}

	for _, obj := range *menuList {
		var ztree common.Ztree
		ztree.Title = obj.MenuName
		ztree.Id = obj.MenuId
		ztree.Name = svc.transMenuName(obj.MenuName, permsFlag)
		ztree.Pid = obj.ParentId
		if isCheck {
			tmp := util.String(obj.MenuId) + obj.Perms
			tmpcheck := false
			for j := range *roleMenuList {
				if strings.Compare((*roleMenuList)[j], tmp) == 0 {
					tmpcheck = true
					break
				}
			}
			ztree.Checked = tmpcheck
		}
		result = append(result, ztree)
	}
	return &result, nil
}

func (svc *SysMenuService) transMenuName(menuName string, permsFlag bool) string {
	if permsFlag {
		return "<font color=\"#888\">&nbsp;&nbsp;&nbsp;" + menuName + "</font>"
	} else {
		return menuName
	}
}

func (svc *SysMenuService) InitChildMap(menus []sysEntity.SysMenu) map[int64][]*sysEntity.SysMenu {
	childrenMap := make(map[int64][]*sysEntity.SysMenu)
	for i, _ := range menus {
		if menus[i].MenuType == "F" { //忽略按钮
			continue
		}
		//每个menu都预设子菜单项
		childrenMap[menus[i].MenuId] = make([]*sysEntity.SysMenu, 0)
	}

	for i, _ := range menus {
		if menus[i].MenuType == "F" { //忽略按钮
			continue
		}
		pid := menus[i].ParentId
		//组织父子关系
		childrenMap[pid] = append(childrenMap[pid], &menus[i])
		//svc.GenMenus(&menus[i], menus)
	}
	return childrenMap
}

/****
获取路由地址
2024-11-08 13:59
wangwei
*/
func getRouterPath(menu sysEntity.SysMenu) string {
	//routerPath =
	routerPath := menu.Path
	// 非外链并且是一级目录（类型为目录）
	if int64(0) == menu.ParentId && "M" == menu.MenuType /*&& "1" == menu.IsFrame */ {
		routerPath = "/" + menu.Path
	} else if isMeunFrame(menu) {
		routerPath = "/"
	}
	return routerPath
}

//是否为菜单内部跳转
func isMeunFrame(menu sysEntity.SysMenu) bool {
	return menu.ParentId == int64(0) && "C" == menu.MenuType && menu.IsFrame == "1"
}

/**
 * 获取组件信息
 *
 * @param menu 菜单信息
 * @return 组件信息
 */
func getComponent(menu sysEntity.SysMenu) string {
	var component string = "Layout"
	if menu.Component != "" && !isMeunFrame(menu) {
		component = menu.Component
	} else if menu.Component != "" && isParentView(menu) {
		component = "ParentView"
	}
	return component
}

/**
 * 是否为parent_view组件
 *
 * @param menu 菜单信息
 * @return 结果
 */
func isParentView(menu sysEntity.SysMenu) bool {
	var isParent bool = true
	if menu.ParentId != 0 && "M" == menu.MenuType {
		return isParent
	}
	return false
}

/**
 * 获取路由名称
 *2024-11-08 16:17
 * @param menu 菜单信息
 * @return 路由名称
 */
func getRouteName(menu sysEntity.SysMenu) string {
	routerName := util.Capitalize(menu.Path)
	// 非外链并且是一级目录（类型为目录）
	if isMeunFrame(menu) {
		routerName = ""
	}
	return routerName
}

/**
 * 构建前端路由所需要的菜单
 *
 * @param menus 菜单列表
 * @return 路由列表
 */
func buildMenus(menus []sysEntity.SysMenu) []*sysEntity.RouterVo {
	//todo
	return nil
}

/***
 * 根据父节点的ID获取所有子节点
 */
func getChildPerms(list []sysEntity.SysMenu, parentId int) []sysEntity.SysMenu {
	returnList := make([]sysEntity.SysMenu, 0)
	for _, t := range list {
		if t.ParentId == int64(parentId) {
			t.Children = recursionFn(list, t)
			returnList = append(returnList, t)
		}

	}
	return returnList
}

func recursionFn(list []sysEntity.SysMenu, t sysEntity.SysMenu) []sysEntity.SysMenu {
	allChildren := []sysEntity.SysMenu{t}

	// 得到子节点列表
	childList := getChildList(list, t)
	t.Children = childList
	for _, tChild := range childList {
		if hasChild(list, tChild) {
			// 递归获取子节点的所有子节点，并将其添加到allChildren列表中
			allChildren = append(allChildren, recursionFn(list, tChild)...)
		} else {
			allChildren = append(allChildren, tChild)
		}
	}
	return allChildren
}

/**
 * 得到子节点列表
 */
func getChildList(list []sysEntity.SysMenu, t sysEntity.SysMenu) []sysEntity.SysMenu {
	tlist := make([]sysEntity.SysMenu, 0)
	for _, menu := range list {
		if menu.ParentId == t.MenuId {
			tlist = append(tlist, menu)
		}
	}
	return tlist
}

/***
判断是否有子节点
*/
func hasChild(list []sysEntity.SysMenu, t sysEntity.SysMenu) bool {
	return len(getChildList(list, t)) > 0
}

/***
菜单列表数据
*/
func GetMenuList(c *gin.Context) {
	restlist := make([]*sysEntity.SysMenu, 0)
	//获取登录用户信息
	sysUser := GetProfile1(c)

	//超管用户
	if sysUser.UserName == "admin" {
		roleErr := config.GormDb.Model(&sysEntity.SysMenu{}).Table("sys_menu ").
			Select(    "menu_id", "menu_name", "parent_id", "order_num", "path", "component", "'query'", "is_frame", "is_cache",
			"menu_type", "visible", "status", "ifnull(perms,'') as perms", "icon", "create_time").
			Where("LOWER(1) = LOWER(?)", 1).Scan(&restlist).Error
		if roleErr != nil {
			common.ReturnError(c, constant.ERRORCODE(), constant.ERRORMSG()+",错误详细信息为： "+util.MapToJson(restlist), "", int64(len("")))
			panic("")
		}
		common.ReturnSucess(c, constant.SUCCESSCODE(), constant.SUCCESSMSG(), restlist, int64(len(restlist)))
	}else {
		//todo 自定义权限用户
	}
}
